/**
 * 拦截器
 */

import Taro from "@tarojs/taro";
import { HTTP_STATUS } from "../constants";

const customInterceptor = (chain) => {
  const requestParams = chain.requestParams;

  return chain.proceed(requestParams).then((res) => {
    if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
      return Promise.reject("请求资源不存在");
    } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
      return Promise.reject("服务端出现了问题");
    } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
      // TODO 根据自身业务修改
      // return Promise.reject("没有权限访问");
    } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
      return Promise.reject("需要鉴权");
    } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
      let data = res.data;

      if (data.bstatus.code != "200") {
        if (data.bstatus.code == 401) {
        } else {
          Taro.showToast({
            title: data.bstatus.desc,
            icon: "none",
            duration: 2000,
          });
        }
      } else {
        //兼容特殊形式的---不消除loading
        if (data && data.data) {
          if (
            data.data.rechargeOrderStatus != 6 &&
            data.data.logOutDealStatus != "OS20"
          ) {
            Taro.hideLoading();
          }
        } else {
          Taro.hideLoading();
        }
      }
      return Promise.resolve(data);
    }
  });
};

const interceptors = [customInterceptor, Taro.interceptors.logInterceptor];

export default interceptors;
